package com.heima.wemedia.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/21
 */
@Service
@Slf4j
public class WmMaterialServiceImpl
        extends ServiceImpl<WmMaterialMapper, WmMaterial>
        implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;

    private static final Integer WM_MATERIAL_TYPE_IMAGE = 0;
    private static final Integer WM_MATERIAL_COLLECTION_NOT = 0;

    /**
     * 素材管理-图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (ObjectUtil.isEmpty(multipartFile)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //上传图片到minIO
        String filename = UUID.randomUUID().toString().replaceAll("-","");
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileUrl = null;
        try {
            fileUrl = fileStorageService.uploadImgFile(
                    "", filename + suffix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileUrl:{}",fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-图片上传失败！");
        }
        //保存数据
        WmMaterial material = new WmMaterial();
        material.setUserId(WmThreadLocalUtil.getUserId());
        material.setUrl(fileUrl);
        material.setType(WM_MATERIAL_TYPE_IMAGE);
        material.setIsCollection(WM_MATERIAL_COLLECTION_NOT);
        material.setCreatedTime(new Date());
        this.save(material);
        //返回结果
        return ResponseResult.okResult(material);
    }

    /**
     * 素材管理-素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getListMaterial(WmMaterialDto dto) {
        //检查分页参数
        dto.checkParam();
        dto.setSize(Math.max(dto.getSize(), WemediaConstants.DEFAULT_PAGE_SIZE));
        //构造查询条件
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        Short isCollection = dto.getIsCollection();
        if (ObjectUtil.isNotEmpty(isCollection) && isCollection == 1) {
            wrapper.eq(WmMaterial::getIsCollection, isCollection);
        }
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUserId());
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //分页查询
        page = this.page(page, wrapper);
        //构造返回值
        ResponseResult responseResult = new PageResponseResult(
                dto.getPage(), dto.getSize(), (int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 素材管理-删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        this.removeById(id);
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        newsMaterialMapper.delete(wrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 素材管理-收藏/取消收藏
     * @param id
     * @param isCollection
     * @return
     */
    @Override
    public ResponseResult isCollection(Integer id, Integer isCollection) {
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial material = new WmMaterial();
        material.setId(id);
        material.setIsCollection(isCollection);
        this.updateById(material);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
